package com.crm.user.controller;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crm.base.annotation.Authority;
import com.crm.base.controller.BaseController;
import com.crm.customers.model.Paid;
import com.crm.customers.model.CommissionCustomer;
import com.crm.customers.model.ContactsDynamicInfo;
import com.crm.customers.model.Contract;
import com.crm.customers.model.CustomerInfo;
import com.crm.customers.service.ContactsDynamicInfoService;
import com.crm.customers.service.ContractPerformanceService;
import com.crm.customers.service.ContractService;
import com.crm.customers.service.CustomerService;
import com.crm.customers.service.PaidService;
import com.crm.im.core.constant.IMConstant;
import com.crm.im.core.model.Message;
import com.crm.im.core.session.DefaultSessionManager;
import com.crm.im.core.session.IMSession;
import com.crm.sys.model.CallLog;
import com.crm.sys.model.Department;
import com.crm.sys.model.Role;
import com.crm.sys.model.SysMessage;
import com.crm.sys.model.SysTerm;
import com.crm.sys.model.UserHistoryMessage;
import com.crm.sys.push.SystemMessagePusher;
import com.crm.sys.service.FilesInfoService;
import com.crm.sys.service.SysService;
import com.crm.user.model.ImFriendUserData;
import com.crm.user.model.ImUserData;
import com.crm.user.model.UserAccount;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.Authorization;
import com.crm.util.CommonUtil;
import com.crm.util.Constants;
import com.crm.util.Pager;
import com.crm.util.StringUtil;
import com.google.common.base.Strings;
import com.google.gson.Gson;
@Controller
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private SysService sysService;
	@Autowired
	private FilesInfoService filesInfoService;
	@Autowired
	private DefaultSessionManager sessionManager;
	@Autowired
	private SystemMessagePusher systemMessagePusher;
	@Autowired
	private ContactsDynamicInfoService contactsDynamicInfoService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private PaidService paidService;
 
	/*@Autowired
	private CustomerService customerService;
	@Autowired
	private ResumeService resumeService;*/
	/**
	 * @return
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String toIndex(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		//避免登录多个账号
		UserAccount user =  getLoginUser();
		if(user!=null&&user.getId()>0){
			return  "redirect:/manage"; 
		} 
		String ck = check(request);
		return "login";//ck+"login";//"login";
	}
	
	@RequestMapping(value = "/user/im", method = RequestMethod.GET)
	public String toImIndex(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 
		return  "mobile/im"; 
	}
	
	
	/**
	 * 待办列表
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/mytodolist", method = RequestMethod.GET)
	public String toDolist(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		ContactsDynamicInfo cinfo = new ContactsDynamicInfo();
		cinfo.setCreateuser(getLoginUser().getId());
		Pager  pager = contactsDynamicInfoService.getContactsDynamicInfo(cinfo, getSkipToPage(), pageSize);
		request.setAttribute("pager", pager);
		return "/usermanage/todolist";
	}
	
	
	/**
	 * 话单列表
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/mycallloglist")
	public String callLoglist(@ModelAttribute CallLog  log,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
 
		log.setCreateuser(getLoginUser().getId());
		log.setKeyWord(getLoginUser().getInfo().getNickname());
		if(StringUtils.isEmpty(log.getSttime())) {
			log.setSttime(CommonUtil.getCurrentDate());
		}
		if(StringUtils.isEmpty(log.getEntime())) {
			log.setEntime(CommonUtil.getCurrentDate());
		}
		
		List<CallLog>  clist = sysService.getCallLogList(log, getSkipToPage(), pageSize);
		Map   map = sysService.getCallLogData(log);
		Pager pager = new Pager(getSkipToPage(), pageSize);
		pager.setResultList(clist);
		Map<String, Object> params = new HashMap<String, Object>();
		
		
		
		params.put("KeyWord",log.getKeyWord());
		params.put("type", log.getType());
		params.put("sttime", log.getSttime());
		params.put("entime", log.getEntime());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("map", map);
		return "/callcenter/callloglist";
	}
	
	
	/**
	 * 话单列表管理
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/managecallloglist")
	public String managecallLoglist(@ModelAttribute CallLog  log, @RequestParam(value="uid", required=false)   Long uid,    HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
 
		Long deptid = getLoginUser().getInfo().getDeptid();
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		
		 if(uid!=null&&uid>0) {
			 log.setCreateuser(uid);
			 UserInfo  uinfo =  userService.getUserInfo(uid);
			 if(uinfo!=null && StringUtils.isNotEmpty(uinfo.getNickname())) {
				 log.setKeyWord(uinfo.getNickname());
			 }
		 }
		if(StringUtils.isEmpty(log.getSttime())) {
			log.setSttime(CommonUtil.getCurrentDate());
		}
		if(StringUtils.isEmpty(log.getEntime())) {
			log.setEntime(CommonUtil.getCurrentDate());
		}
		
		List<CallLog>  clist = sysService.getCallLogList(log, getSkipToPage(), pageSize);
		Map   map = sysService.getCallLogData(log);
		Pager pager = new Pager(getSkipToPage(), pageSize);
		pager.setResultList(clist);
		Map<String, Object> params = new HashMap<String, Object>();
		
		
		
		params.put("KeyWord",log.getKeyWord());
		params.put("uid", uid);
		params.put("type", log.getType());
		params.put("sttime", log.getSttime());
		params.put("entime", log.getEntime());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("map", map);
		request.setAttribute("userlist", userlist);
		
		return "/callcenter/managecallloglist";
	}
	
	/**
	 * 文件上传
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 *  参考API http://fex.baidu.com/ueditor/#dev-request_specification   百度图片上传
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/pictures", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile(@RequestParam MultipartFile  file,
			HttpServletResponse response, HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
			UserAccount  u = getLoginUser();
			Long uid = u.getId();
		 	String path=request.getSession().getServletContext().getRealPath("upload/img/user/");
		 	int result = filesInfoService.saveUserPicture(file, uid, path);
		 	Map<String,String> map = new HashMap<String,String>();
			 if(result>0){
					map.put("state","1");
					map.put("url","/upload/img/user/B"+uid+".jpg?"+new Date().getTime());
					//更新数据库
					UserInfo uinfo = new UserInfo();
					uinfo.setId(getLoginUser().getInfo().getId());
					uinfo.setPhoto("/upload/img/user/B"+uid+".jpg");
					userService.saveUserInfo(uinfo);
					//更新session
					u.getInfo().setPhoto(uinfo.getPhoto());
					u.getInfo().setAvatar(uinfo.getPhoto());
					request.getSession().setAttribute("user", u); 
			  }else{
				  map.put("state","0");
				  map.put("msg", "上传过程中出现错误，请重新上传");  
			  }
			  return  JSON.toJSONString(map);
	}
	/** 
	 * 图片上传
	 * @param file
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/imgupload", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImgFile(@RequestParam MultipartFile  file,
			HttpServletResponse response, HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
			UserAccount  u = getLoginUser();
			Long uid = u.getId();
		 	String path=request.getSession().getServletContext().getRealPath("upload/img/temp/");
		 	String files = filesInfoService.savePicture(file,uid.toString()+StringUtil.getUUID(), path);
		 	Map<String,Object> map = new HashMap<String,Object>();
		 	 Map<String,String> submap = new HashMap<String,String>();
			 if(files.length()>0){
					map.put("code","0");
					map.put("msg", "上传过成功");  
				    submap.put("src", "/upload/img/temp/"+files+"?"+new Date().getTime());
			  }else{
				  submap.put("src", "");
				  map.put("code","1");
				  map.put("msg", "上传过程中出现错误，请重新上传");  
			  }
			  map.put("data",submap);
			  return  JSON.toJSONString(map);
	}
	
	
	/** 
	 * 文件上传
	 * @param file
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/fileupload", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String uploadAllFile(@RequestParam MultipartFile  file,
			HttpServletResponse response, HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
			UserAccount  u = getLoginUser();
			Long uid = u.getId();
		 	String path=request.getSession().getServletContext().getRealPath("upload/file/temp/");
		 	String files = filesInfoService.saveFiles(file, uid.toString()+StringUtil.getUUID(), path);
		 	Map<String,Object> map = new HashMap<String,Object>();
		 	 Map<String,String> submap = new HashMap<String,String>();
			 if(files.length()>0){
					map.put("code","0");
					map.put("msg", "上传过成功");  
				    submap.put("src", "/upload/file/temp/"+files+"?"+new Date().getTime());
				    submap.put("name", file.getOriginalFilename());
			  }else{
				  submap.put("src", "");
				  map.put("code","1");
				  map.put("msg", "上传过程中出现错误，请重新上传");  
			  }
			  map.put("data",submap);
			  return  JSON.toJSONString(map);
	}
	
	@RequestMapping(value = "/user/message", method = RequestMethod.GET)
	public String userMessage(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		SysMessage ms = new SysMessage();
		ms.setType(1);
		ms.setIsread(0);
		ms.setReceiveuser(getLoginUser().getId());
		List<SysMessage>  msgList = sysService.getMessageList(ms);
		sysService.updateMessageState(ms);
		request.setAttribute("msgList", msgList);
		return "/usermanage/message";
	}
	
	
	@RequestMapping(value = "/user/messagecount", method = RequestMethod.GET)
	@ResponseBody
	public String userMessageCount(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		SysMessage ms = new SysMessage();
		ms.setType(1);
		ms.setReceiveuser(getLoginUser().getId());
		int count = sysService.getMessageCount(ms);
		return JSONArray.toJSONString(count);
	}
	
	/**
	 * 聊天记录
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/historymessageajax", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String userHistoryMessages(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		UserHistoryMessage ms = new UserHistoryMessage();
		ms.setSenduser(getLoginUser().getId());
		ms.setReceiveuser(Long.parseLong(request.getParameter("id")));
		List<UserHistoryMessage>  msgList = sysService.getUserHistoryMessage(ms, getSkipToPage(), pageSize);
		Map<String,List<UserHistoryMessage>> map = new HashMap();
		map.put("data", msgList);
		return JSONArray.toJSONString(map);
	}
	
	/**
	 * 聊天记录
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/historymessage", method = RequestMethod.GET)
	public String userHistoryMessagesPage(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		UserHistoryMessage ms = new UserHistoryMessage();
		ms.setSenduser(getLoginUser().getId());
		ms.setReceiveuser(Long.parseLong(request.getParameter("id")));
		List<UserHistoryMessage>  msgList = sysService.getUserHistoryMessage(ms, getSkipToPage(), pageSize);
		Pager pager = new Pager(getSkipToPage(), pageSize);
		pager.setResultList(msgList);
		request.setAttribute("pager", pager);
		return "/usermanage/historymessage";
	}
	
	
	/** 
	 *  取得所有用户
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/getalluser", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getAllUser(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		   List<UserInfo> all = userService.getAllUser();
			if(getLoginUser()!=null){
				
				Map map = new HashMap();
				ImUserData  us = new ImUserData();
				us.setCode("0");
				us.setMsg("");
				map.put("mine", getLoginUser().getInfo());
				map.put("group", new ArrayList());
				List fuList = new ArrayList();
				List<Department>  depts = sysService.getDepartmentListAll(null);
				for(Department dep:depts){
					List<UserInfo> tempList = new ArrayList();
					ImFriendUserData fu = new ImFriendUserData();
					for(UserInfo uinfo:all){
						try{
							   if(uinfo.getDeptid().equals(dep.getId())){
								   tempList.add(uinfo);
							   }
						}catch(Exception e){ } 
					} 
					if(tempList.size()>0){
						fu.setList(tempList);
						fu.setGroupname(dep.getName());
						fu.setId(dep.getId()); 
						fuList.add(fu);
					}
					
				}
				 
				map.put("friend",fuList);
				/*"groupname": "前端码屌"
				      ,"id": 1
				      ,"online": 2
				      ,"list"*/
				
				us.setData(map);
				return JSONArray.toJSONString(us);
			}else{
				return JSONArray.toJSONString("");
			}
	}
	
	

	@RequestMapping(value = "/user/saveuserinfo", method = RequestMethod.POST)
	public String addCustomerInfo(@ModelAttribute UserInfo  info,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request) throws Exception{
		UserAccount  ua = getLoginUser();
		info.setId(ua.getInfo().getId());
		userService.saveUserInfo(info);
		  attr.addFlashAttribute("success", "保存成功!");
		  ua.setInfo(userService.getUserInfo(ua.getId()));
		  //更新session
		 getSession().setAttribute("user",ua);
		 attr.addFlashAttribute("user",ua);//.setAttribute("user", ua);
		return "redirect:/user/userinfo";
	}
	
	@Autowired
	public ContractPerformanceService contractPerformanceService;
	/**
	 *  后台首页
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@Authority(validdateURL=true)
	@RequestMapping(value = "/manage", method = RequestMethod.GET)
	public String manageIndex(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		List<SysTerm>  menu = sysService.getRoleMenu(getLoginUser().getInfo().getRid());
		request.setAttribute("menu", JSONArray.toJSONString(menu));
		request.setAttribute("robot", Constants.ROBOTNAME);
		request.setAttribute("menuobj", menu);
		String ck =  check(request);
		//ck+"index"; 
		return "/index"; 
	}
	
	@RequestMapping(value = "/user/main", method = RequestMethod.GET)
	public String manageUserIndex(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		
		Integer pageNo = 1;
		Integer pageSize = 1;
		Long id = getLoginUser().getId();
		
		//获取已录入客户和简历
		List<CustomerInfo> lrkhlist = customerService.getCustomerInfoListByTypes(1, id, pageSize, pageNo);
		List<CustomerInfo> lrjllist = customerService.getCustomerInfoListByTypes(2, id, pageSize, pageNo);
		request.setAttribute("lrkhlist", lrkhlist);
		request.setAttribute("lrjllist", lrjllist);
		
		//获取已联系和预约的客户
		List<CustomerInfo> lxkhlist = customerService.getCustomerInfoListByTypes(3, id, pageSize, pageNo);
		List<CustomerInfo> yykhlist = customerService.getCustomerInfoListByTypes(4, id, pageSize, pageNo);
		request.setAttribute("lxkhlist", lxkhlist);
		request.setAttribute("yykhlist", yykhlist);
		
		
		//预约客户总数量
		ContactsDynamicInfo cinfo = new ContactsDynamicInfo();
		cinfo.setCreateuser(getLoginUser().getId());
		Pager  pager = contactsDynamicInfoService.getContactsDynamicInfo(cinfo, getSkipToPage(), pageSize);
		request.setAttribute("yyallcount", pager.getTotalSize());  
		
		CustomerInfo ci = new CustomerInfo();
		ci.setType(1);
		ci.setUid(getLoginUser().getId());
		Pager pagerOne = customerService.getCustomerInfoList(ci, pageNo, pageSize);
		//企业客户总数量
		request.setAttribute("qyallcount", pagerOne.getTotalSize());  
		ci.setType(0);
		//人才客户总数量
		Pager pagerTwo = customerService.getCustomerInfoList(ci, pageNo, pageSize);
		request.setAttribute("rcallcount", pagerTwo.getTotalSize());  
		//取得今日签订的合同数量
		Contract c = new Contract();
		c.setUid(getLoginUser().getId());
		int contractCount =  contractService.getSigningByDay(c);
		request.setAttribute("contractCount", contractCount);
		
		List<CallLog>  cllist =   sysService.getTimesUserCallLogList();
		request.setAttribute("calllist", cllist);
		
		Map<String,Object> map = contractPerformanceService.getPerFormanceByUid(getLoginUser().getId());
		Integer yj[]=(Integer[])map.get("yj");
		String  yjjson = JSON.toJSONString(yj);
		map.put("yjjson", yjjson);
		request.setAttribute("yj", map);
		request.setAttribute("totalmoneyFromDays",map.get("totalmoneyFromDays") );
		request.setAttribute("allUserPerformancelist",map.get("allUserPerformancelist") );
		return "/usermain"; 
	}
	
	/**
	 * 更新用户在线状态
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/onlinestate", method = RequestMethod.GET)
	@ResponseBody
	public String manageUserOnlineState(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
	    String state = request.getParameter("state");
	    if(StringUtils.isNotEmpty(state)){
	    	state = IMConstant.MessageType.TYPE_OFFLINE;
	    }else{
	    	state = IMConstant.MessageType.TYPE_ONLINE;
	    }
	    
	    List<IMSession>  sessionList = sessionManager.queryAll();
		for(IMSession s:sessionList){
			String user = getLoginUser().getId().toString();
			if(!s.getAccount().equals(user)){//判断不是自己账号
				Message  msg = new Message();
				msg.setType(state);//消息类型
				msg.setReceiver(s.getAccount());
				msg.setContent(user);
				systemMessagePusher.push(msg); 
			} 
		} 
		return "1"; 
	}
	
	
	
	/**
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String userLogin(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes attr) throws Exception{
		
		//先判断是否过期
				boolean b = Authorization.isOutOfTime();
				if (!b){
					//过期
					getSession().setAttribute("errormsg", "授权已过期!请联系经销商延长服务期限.");
					attr.addFlashAttribute("action",1);
					return "redirect:/";
				}
				getSession().setAttribute("action", 1);
		
		getSession().setAttribute("action", 1);
		/*String uname =  request.getParameter("uname"); //账号
		String upwd = request.getParameter("upwd"); //密码
*/		String uname =  request.getParameter("account"); //账号
		String upwd = request.getParameter("password"); //密码
		String codenum = request.getParameter("codenum"); //密码
		
	/*	String kaptchaExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(codenum != null && kaptchaExpected.equals(codenum.toLowerCase())){*/
			UserAccount  user = new UserAccount();
			user.setAccount(uname);
			user.setPassword(upwd);
			UserAccount  result = userService.validateLoginUser(user);
			if(result!=null&&result.getInfo()!=null){
				setLoginUser(result,response);
				getSession().setAttribute("errormsg", null);
			}else{
				getSession().setAttribute("errormsg", "账号或密码错误!");
				attr.addFlashAttribute("action",1);
				return "redirect:/";
			}
		/*}else{
			getSession().setAttribute("errormsg", "验证码错误!");
			attr.addFlashAttribute("action",1);
			return "redirect:/";
		}*/
		request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,")(*&^$#@@!#$");
		
		return  "redirect:/manage"; 
	}
	
	/**
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public String userLogin(HttpServletResponse response) throws Exception{
		removeUser(response);
		return  "redirect:/"; 
	}
	
	
	
	/**
	 *  用户注册
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String userRegister(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String uname =  request.getParameter("account"); //账号
		String upwd = request.getParameter("password"); //密码
		
		if(StringUtils.isNotEmpty(uname)&&StringUtils.isNotEmpty(upwd)){
			UserAccount  user = new UserAccount();
			user.setAccount(uname);
			user.setPassword(upwd);
			user.setState(0);
		  	boolean  result = userService.saveUser(user);
		  	if(result){
		  		redirectAttributes.addFlashAttribute("success", "请先完善您的个人信息!");
		  		redirectAttributes.addFlashAttribute("comp", 1);
				 getSession().setAttribute("user",user);
				return "redirect:/manage";
		  	}
		  	getSession().setAttribute("errormsg", "该账号已被注册!");
		}else{
			getSession().setAttribute("errormsg", "请输入账号及密码!");
		}
	  	getSession().setAttribute("action", 2);
		return "redirect:/"; 
	}
	
	/**
	 *  用户信息展示
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/userinfo")
	public String userInfoShow(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
           
            request.setAttribute("user",  getLoginUser());
	  		return "/usermanage/userinfo/userinfo";
	}
	
	
	/**
	 *  用户信息展示
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/userinfopage")
	public String userInfoShowPage(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		    String uid = request.getParameter("id");
		    if(StringUtils.isNotEmpty(uid)){
		    	   Long id = Long.parseLong(uid);
		            UserAccount  user =  userService.getUserAccountInfoById(id);
		            request.setAttribute("userobj", user);
		    }
	  		return "/usermanage/userinfo/adduserinfo";
	}
	
	@RequestMapping(value = "/user/saveuserinfopage", method = RequestMethod.POST)
	public String addUserInfo(@ModelAttribute UserInfo  info,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request) throws Exception{
		
		
		String uname =  request.getParameter("account"); //账号
		String upwd = request.getParameter("password"); //密码
		
		if(info.getId()!=null){
			boolean result = userService.saveUserInfo(info);
			return "redirect:/user/userinfopage?id="+info.getUid();
		}else{
			if(StringUtils.isNotEmpty(uname)&&StringUtils.isNotEmpty(upwd)){
				UserAccount  user = new UserAccount();
				user.setAccount(uname);
				user.setPassword(upwd);
				user.setState(0);
			  	boolean  result = userService.saveUser(user);
			  	if(result){
			  		 info.setId(user.getInfo().getId());
			  		info.setUid(user.getId());
			  		userService.saveUserInfo(info); 
			  		return "redirect:/user/userinfopage?id="+user.getId();
			  	}
			}
		}
		 
		return "redirect:/user/userinfopage";
	}
	
	/**
	 *  ajax验证用户名是否被占用
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/validateAccount", method = RequestMethod.GET)
	@ResponseBody
	public String validateUserAccount(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String uname =  request.getParameter("account"); //账号 
		boolean result =  userService.validateUserAccount(uname);
		return JSONArray.toJSONString(result);
	 
	}
	
	/**
	 *  账号管理
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/updatepassword", method = RequestMethod.POST)
	@ResponseBody
	public String updatePassword(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String password=getLoginUser().getPassword();//原密码
		String upwd = request.getParameter("password"); //输入原密码
		String newupwd = request.getParameter("newpassword"); //新密码
		
		
			UserAccount  user = new UserAccount();
			//user.setUpdateUser(String.valueOf(getLoginUser().getId()));
			user.setId(getLoginUser().getId());
			//System.out.println("^^^"+getLoginUser().getId());
			user.setPassword(newupwd);
			int result=userService.updatePassword(user,password,upwd);
		   /* if(result==0){ 
		        redirectAttributes.addFlashAttribute("success", "原密码错误!");
		    }else{
		    	redirectAttributes.addFlashAttribute("success", "密码修改成功!");
		    }*/
		 return    JSONArray.toJSONString(result);
	  	//boolean  result = userService.saveUser(user);
	  	
		
	  	
	}
	
	
	/**
	 * 用户查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@Authority(validdateURL=true)
	@RequestMapping(value = "/user/getuserlist{k}" )
	public String getUserList(@ModelAttribute UserInfo user,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		   Pager  pager = userService.getUserList(user, getSkipToPage(), pageSize);
		   Map<String,Object> params = new HashMap<String,Object>();
			 params.put("keyWord", user.getKeyWord());
			 params.put("deptid", user.getDeptid());
			 pager.setParams(params);
		   pager.setUrl("/user/getuserlist");
		    request.setAttribute("pager", pager );
		   return "/sysmanage/user";
	}
	/**
	 *  用户绑定角色列表的查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/getrolelist", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getRole(@ModelAttribute Role role,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		     List<Role>  list= userService.getRole(role);
		   
		    return JSONArray.toJSONString(list);
	}
	/**
	 *  用户绑定角色保存
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/saveRole", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveRole(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String uid=request.getParameter("uid");
		String rid=request.getParameter("rid");
		 
		    int result= userService.saveRole(uid,rid);
		   
		    return JSONArray.toJSONString(result);
	}
	/**
	 *  用户修改的ID查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/getuserbyid" ,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getUserByid(@ModelAttribute UserInfo user,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String aid=request.getParameter("id");
		user= userService.getUserByid(Long.parseLong(aid));
		 Gson gson = new Gson();
		 return gson.toJson(user);
	}
	/**
	 *  用户修改的保存
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/saveuserbyid" ,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String saveUserByid(@ModelAttribute UserInfo user,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		int result=userService.saveUserByid(user);
		return JSONArray.toJSONString(result);
	}
	/**
	 *  用户绑定行业
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/savecalling", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveCalling(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String uids=request.getParameter("id");
		String callingids=request.getParameter("callingid");
		 int result= userService.saveCalling(uids,callingids);
		 return JSONArray.toJSONString(result);
	}
	/**
	 *  查询显示通讯录(根据部门显示)
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/getcallinglist", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getCallingList(@ModelAttribute Department dt,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		List<Department> list = userService.getDeptUserList(dt);
		 return JSONArray.toJSONString(list);
	}
	/**
	 *  根据部门查询用户列表
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/getuserdtpidlist", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUserdtpidList(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String deptid=request.getParameter("deptid");
		List<UserInfo> userlist=userService.getUserListByDeptId(Long.valueOf(deptid));
		    return JSON.toJSONString(userlist);
	}
	
	/**
	 * 根据部门查询部门及子部门下所有的用户列表
	 * */
	@RequestMapping(value = "/user/getuserlistbydtid", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUserListByDtid(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String deptid=request.getParameter("deptid");
		List<UserInfo> userlist=userService.getAllUserListByDeptId(Long.valueOf(deptid));
		return JSON.toJSONString(userlist);
	}
	
	/**
	 *  资源调配
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value = "/user/updateusercout", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String updateUserCout(@ModelAttribute CustomerInfo info,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String ids="";
		String creatid=request.getParameter("creatid");//离职ID
		String updateid=request.getParameter("updateid");//接受ID
		info.setCreateuser(creatid);
		info.setState(10);//设置为所属状态条件
		List<CustomerInfo> list=sysService.getCustomerList(info);
		for(CustomerInfo cinfo:list){
			 if(ids == ""){
				  ids=String.valueOf(cinfo.getId());
			  }else{
				  ids +="," +cinfo.getId() ;
			  }
		}
		Long infoid= getLoginUser().getId();
		int result= sysService.saveCustomerCreatuserUpdate(ids,updateid,infoid);
		 return JSONArray.toJSONString(result);
		
	}*/
	/**
	 *  删除用户
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/user/deleteuseraccount", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String deleteUserAccount(@ModelAttribute UserAccount ua,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String aids=request.getParameter("aids");//用户ID
		int result=0;
		result=userService.deleteUserAccount(aids, String.valueOf(getLoginUser().getId()));
		 return JSONArray.toJSONString(result);
	}
	
	/**
	 * 修改密码
	 * */
	@RequestMapping(value="/user/updateuserpwd",method=RequestMethod.POST)
	@ResponseBody
	public String updateUserPwd(String oldpwd,String newpwd,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//先判断传入的数据是否不为空
		if (oldpwd == null || newpwd == null) {
			return JSON.toJSONString(0);
		}
		//原密码
		String password=getLoginUser().getPassword();
		UserAccount  user = new UserAccount();
		user.setId(getLoginUser().getId());
		user.setPassword(newpwd);
		int result = userService.updatePassword(user, password, oldpwd);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 重置密码，将密码重置为123456
	 * */
	@RequestMapping(value="/user/resetuserpwd")
	@ResponseBody
	public String resetUserPwd(String ids,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		
		String newpwd = "123456";
		if (ids != null && ids.length() > 0) {
			String idskey[] = ids.split(",");
			UserAccount  user = new UserAccount();
			for (String id : idskey) {
				if(Long.parseLong(id)==1) {
					continue ;
				}
				user.setId(Long.parseLong(id));
				user.setPassword(newpwd);
				userService.resetUserPwd(user);
			}
			return JSON.toJSONString(1);
		} else {
			return JSON.toJSONString(0);
		}
	}
	
	/**
	 * ajax获取所有用户列表
	 * 根据type来判定获取哪一种列表
	 * type=1部门-用户（value=uid）
	 * */
	@RequestMapping(value="/user/getuserjson",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getAllUserListByAjax(Integer type,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		if (type == 1) {
			List<UserInfo> list = userService.getUserInfoListWithDept();
			return JSON.toJSONString(list);
		}
		
		return null;
	}
	
	
 
	
	/**
	 * 进入报销事项列表页
	 * */
	@RequestMapping(value="/user/paidmanagelist")
	public String managePaidListPage(@ModelAttribute Paid p,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		List<UserInfo> userlist = userService.getUserInfoListWithDept();
		Integer pageNo = getSkipToPage();
		//获取报销
		int totalmoney = paidService.getPaidTotalMoney(p);
		List<Paid> list = paidService.getCallLogList(p, pageNo, pageSize) ;
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("state", p.getState());
		params.put("sttime", p.getSttime());
		params.put("entime", p.getEntime());
		params.put("keyWord", p.getKeyWord());
		params.put("uid",p.getCreateuser());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("userlist", userlist);
		request.setAttribute("totalmoney", totalmoney);
		return "/customermanage/paidmanagelist";
	}
	/**
	 * 进入报销事项列表页
	 * */
	@RequestMapping(value="/user/paidlist")
	public String intoPaidListPage(@ModelAttribute Paid p,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = getSkipToPage();
		//获取报销
		 
		p.setCreateuser(getLoginUser().getId());
		int totalmoney = paidService.getPaidTotalMoney(p);
		List<Paid> list = paidService.getCallLogList(p, pageNo, pageSize) ;
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		pager.setUrl("/customer/paidlist");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("state", p.getState());
		params.put("sttime", p.getSttime());
		params.put("entime", p.getEntime());
		params.put("keyWord", p.getKeyWord());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("uid", getLoginUser().getId());
		request.setAttribute("totalmoney", totalmoney);
		return "/customermanage/paidlist";
	}
	
	/**
	 * 保存报销事项
	 * */
	@RequestMapping(value="/user/savepaid")
	@ResponseBody 
	//@RequestParam("cids") Long cids[],@RequestParam("uids") Long uids[],
	public String savePaid(@ModelAttribute Paid c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		//所以第一步是把获取的代办存到数据库
		//将审批状态设置为0
		c.setApprovestate(0);
		c.setCreateuser(getLoginUser().getId());
		c.setCreateuserName(getLoginUser().getInfo().getName());
		//保存代办事项
		c = paidService.savePaid(c);
		return JSON.toJSONString(1);
	}
	
	/**
	 * 删除报销内容
	 * */
	@RequestMapping(value="/user/deletepaid")
	@ResponseBody
	public String deleteCommissionCustomer(Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		int result = 0;
		Paid p = new Paid();
		p.setId(id);
		p.setIsdel(1);
		result = paidService.updatePaid(p);
		return JSON.toJSONString(result);
	}
	
	/**
	 *   获取驳回原因
	 * */
	@RequestMapping(value="/user/paidoverrulereason",produces="text/html;charset=UTF-8")
	@ResponseBody 
	//@RequestParam("cids") Long cids[],@RequestParam("uids") Long uids[],
	public String getPaidoverrulereason(@ModelAttribute Paid c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 
		//保存代办事项
		String result  = paidService.getOverruleReason(c);
		return JSON.toJSONString(result);
	}
	
	
	/**
	 * 报销事项详情页
	 * c中只有id
	 * */
	@RequestMapping(value="/user/paidinfo")
	public String PaidInfo(@ModelAttribute Paid c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Paid  info = paidService.getPaidInfoById(c);
		request.setAttribute("paidinfo", info);
		return "/customermanage/paidinfo";
	}
	
	/**
	 * 提交审批
	 * */
	@RequestMapping(value="/user/approvepaid")
	@ResponseBody
	public String approvePaid(Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception  {
		int result = 0;
		Paid c = new Paid();
		c.setId(id);
		c = paidService.getPaidInfoById(c);
		c.setCreateuserName(getLoginUser().getInfo().getName());
		result = paidService.approvePaid(c);
		return JSON.toJSONString(result);
	}
	
	
}
